package top.itaso.app.ui.mediaplayer

import android.media.AudioManager
import android.media.MediaPlayer
import android.util.Log
import android.view.SurfaceHolder
import androidx.lifecycle.ViewModel

class MediaPlayerViewModel : ViewModel() {
    private val URL_MEDIAS = arrayOf(
        "https://dh2.v.netease.com/2017/cg/fxtpty.mp4",
        "https://www.tpv-tech.com/images/video.mp4",
        "http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
    )

    private var mediaPlayer: MediaPlayer = MediaPlayer()

    fun initMediaPlayer(sh: SurfaceHolder) {
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC)
        mediaPlayer.setDisplay(sh)
//        mediaPlayer.setDataSource(getMediaSource())
//        mediaPlayer.prepareAsync()
        mediaPlayer.setOnBufferingUpdateListener(object : MediaPlayer.OnBufferingUpdateListener {
            override fun onBufferingUpdate(mp: MediaPlayer?, percent: Int) {
                Log.d(TAG, "onBufferingUpdate: >>>>>percent=$percent")
            }
        })
        mediaPlayer.setOnPreparedListener(object : MediaPlayer.OnPreparedListener {
            override fun onPrepared(mp: MediaPlayer?) {
                Log.d(TAG, "onPrepared: >>>>>>装载完成")
                mediaPlayer.start()
            }
        })
        mediaPlayer.setOnVideoSizeChangedListener { mp, width, height ->
            Log.d(TAG, "onVideoSizeChanged: >>>>>>width=$width,height=$height")
        }
        mediaPlayer.setOnInfoListener { mp, what, extra ->
            Log.d(TAG, "onInfo: >>>>>>what=$what,extra=$extra")
            false
        }
        mediaPlayer.setOnCompletionListener {
            Log.d(TAG, "onCompletion: >>>>>>播放完成")
        }
        mediaPlayer.setOnErrorListener { mp, what, extra ->
            Log.d(TAG, "onError: >>>>>>播放异常，what=$what,extra=$extra")
            false
        }
    }

    fun getMediaSource(): String {
        return URL_MEDIAS[0]
    }

    fun playMediaSource() {
        if (mediaPlayer != null) {
            mediaPlayer.setDataSource(getMediaSource())
            mediaPlayer.prepareAsync()
        }
    }

    fun stopMediaSource() {
        if (mediaPlayer != null && mediaPlayer.isPlaying) {
            mediaPlayer.stop()
            mediaPlayer.release()
        }
    }

    companion object {
        private const val TAG = "MediaPlayerViewModel"
    }


}